package com.zerui.manager.common.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * <h1>Spring上下文管理类，用来获取注入的对象</h1>
 *
 * @author taskmgr
 */
@Component("appSpringContextTools")
public class SpringContextTools implements BeanFactoryPostProcessor,ApplicationContextAware {
	/**
	 * Spring应用上下文环境
	 */
	private static ConfigurableListableBeanFactory beanFactory;

	// Spring应用上下文环境
	private static ApplicationContext applicationContext;

	/**
	 * <h1>获取spring管理的bean对象</h1>
	 *
	 * @param name
	 *            bean名称
	 * @return bean对象
	 * @throws BeansException
	 *             异常
	 */
	public static Object getBean(String name) throws BeansException {
		return applicationContext.getBean(name);
	}

	/**
	 * 获取类型为requiredType的对象
	 *
	 * @param clz
	 * @return
	 * @throws BeansException
	 */
	public static <T> T getBean(Class<T> clz) throws BeansException {
		T result = (T) beanFactory.getBean(clz);
		return result;
	}

	/**
	 * <h1>判断spring管理的bean对象中是否包含额该bean对象</h1>
	 *
	 * @param name
	 *            bean名称
	 * @return boolean 包含：true，不包含：false
	 */
	public static boolean containsBean(String name) {
		return applicationContext.containsBean(name);
	}

	/**
	 * @return ApplicationContext
	 */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContextTools.applicationContext = applicationContext;
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
		SpringContextTools.beanFactory = configurableListableBeanFactory;
	}
}
